import { connectEventSource } from 'src/utils/utils'
import { amrPanel } from 'src/views/MapCore/MapGlobal/utils/KonvaEvent.js'
import { groupToolsBar, initGroupToolsBar } from 'src/views/MapCore/MapGlobal/utils/MouseEvent'
import { AGVMonitor, areaMonitor } from 'src/views/MapCore/MapGlobal/utils/utils.mqtt'

const deleteAGVMap = new Map(), TIME = 2 // s
let moveModelInfo = {}, eventSourceAMR = null, eventSourceArea = null

export const connectSSE = (canvas, mapGroundCode = '', props = {}) => {
  initGroupToolsBar('AMRs')
  eventSourceAMR && eventSourceAMR.close()
  eventSourceArea && eventSourceArea.close()
  const formatEventMsg = async msg => {
    const { agvStatusCntList = [], agvStatusList = [] } = msg || {}, { status = [], chargeList = [] } = props
    status && status.splice(0) && status.push(...agvStatusCntList)
    chargeList && chargeList.splice(0)
    for (const key in moveModelInfo) deleteAGVMap.set(key, '1')
    for (const amr of (agvStatusList || []).sort((a, b) => a.agvCode - b.agvCode)) {
      deleteAGVMap.set(amr.agvCode, '0')
      chargeList && chargeList.push(amr)
      AGVMonitor(canvas, amr, moveModelInfo, TIME).then(() => {})
    }
    for (const [key, value] of deleteAGVMap) {
      value === '1' &&
      AGVMonitor(canvas, { [key]: value, agvCode: key }, moveModelInfo).then(() => deleteAGVMap.delete(key))
    }
    canvas.findOne('.shapeLayer').batchDraw()
  }
  const formatEventAreaMsg = async msg => {
    for (const alarmArea of (msg || [])) await areaMonitor(canvas, alarmArea, props.alarmAreas)
  }
  eventSourceAMR = connectEventSource(`sse/mapMonitor?mapGroundCode=${mapGroundCode}`, formatEventMsg)
  eventSourceArea = connectEventSource(`sse/mapAreaRuleWarn?mapGroundCode=${mapGroundCode}`, formatEventAreaMsg)
}
export const closeSSE = (canvas, props = {}) => {
  eventSourceAMR && eventSourceAMR.close()
  eventSourceArea && eventSourceArea.close()
  eventSourceAMR = null
  eventSourceArea = null
  deleteAGVMap.clear()
  const { alarmAreas = [], status = [], chargeList = [] } = props
  status && status.splice(0)
  alarmAreas && alarmAreas.splice(0)
  chargeList && chargeList.splice(0)
  moveModelInfo = {}
  amrPanel.value = { visible: false }
  delete groupToolsBar.value.AMRs
  if (!canvas) return
  const layer = canvas.findOne('.AMRs')
  layer && layer.removeChildren() && layer.destroy()
}